package gl.java.umsp.room;

import gl.java.umsp.bean.Room;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
public class RoomPool {
    private Map<String, Room> roomMap = new ConcurrentHashMap<String, Room>();

    private static class SingleHolder {
        final static RoomPool holder = new RoomPool();
    }

    public static RoomPool getInstance() {
        return SingleHolder.holder;
    }

    public Map<String, Room> getAllRoom() {
        return roomMap;
    }

    public Room findRoomByUserID(int userID) {
        Set<String> keys = roomMap.keySet();
        for (String key : keys) {
            Room room = roomMap.get(key);
            if (room.getRoomUserList().containsKey(userID)) {
                return room;

            }
        }
        return null;
    }

    public Room findRoomAndCreateIfNotExist(String roomSession) {
        String[] split = (String[]) Room.checkSession(roomSession);
        if (split != null) {
            String roomID = split[0];
            int gameID = Integer.parseInt(split[1]);
            if (!roomMap.containsKey(roomID)) {
                Room value = new Room(gameID, roomID, roomSession);
                roomMap.put(value.roomID, value);
                return value;
            } else {
                return roomMap.get(roomID);
            }
        } else {
            return null;
        }
    }


    public void put(Room room) {
        if (roomMap.containsKey(room.roomID))
            return;
        roomMap.put(room.roomID, room);
    }

    public void remove(int roomID) {
        if (!roomMap.containsKey(roomID))
            return;
        roomMap.remove(roomID);
    }

}
